<?php

class User extends BaseEntity{

	public static $type = "User";
	public static $rolePerson = 1;
	public static $roleCompany = 2;

	function __construct($id = 0){
		parent::__construct($id);
	}

	function getProfile(){
		return Profile::getProfile($this->id);	
	}
	
	function id(){
		return $this->attributes->id;
	}

	function setPassword($pass){
		$this->attributes->password = $this->getPassword($pass);
	}

	function isAdmin(){
		return $this->admin;
	}

	function getPassword($pass, $skipValidation = false){
		if(!$skipValidation && (strlen($pass) > MAXPASSLENGTH || strlen($pass) < MINPASSLENGTH))
		{
			$this->passwordError = true;
			return $this->attributes->password;
		}
		return md5($pass);
	}

	function updatePosition($latitud,$longitud) {
		$this->latitud = $latitud;
		$this->longitud = $longitud;
		$this->lastPositionUpdate = time();
		$this->save(false);
	}

	function getCompanies(){
		return $this->search("`type` = ".User::$roleCompany);
	}

	static function getAllUsers(){
		$userManage = new User();
		return $userManage->search("type = ".User::$rolePerson);
	}
	
	static function getAllUsersByTime($time){
		$userManage = new User();
		return $userManage->search("type = ".User::$rolePerson . " and lastPositionUpdate > ". $time);
	}
	
	function getMessageNearCompany($distance = 100, $onlyNotSent = true){
		$user = new User();
		$companies = $this->getCompanies();

		$nearCompanies  = array();
		foreach ($companies as $company){
			if($company["id"] != $this->id){
				$km = distance($this->latitud, $this->longitud, $company["latitud"], $company["longitud"]);
				$meters = round($km * 1000);
				/*
				 echo $this->latitud."<br/>";
				 echo $this->longitud."<br/>";
				 echo $company["latitud"]."<br/>";
				 echo $company["longitud"]."<br/>";
				 echo "distance to ".$company["username"]." = $meters mts<br/>";
				 */
				if($meters < $distance){
					array_push($nearCompanies, $company);
				}
			}
		}

		$companyMesagges = new CompanyMessages();
		$nearMessages = Array();
		foreach ($nearCompanies as $company){
			if ($onlyNotSent){
				$messages = $companyMesagges->getActiveMessages($company["id"], $this->id);
			}else{
				$messages = $companyMesagges->getActiveMessages($company["id"]);
			}

			if ($messages){
				foreach ($messages as $m){
					array_push($nearMessages, $m);
				}
			}
		}

		return $nearMessages;
	}

	function getNearUser(){
		$usersNear = array();

		//mock
		if(USEFIXEDUSERS){
			$meters = 0;
			foreach (User::getFixedUsers() as $user){
				$meters = $meters +10;
				$user->meters = $meters;
				$user->profile = Profile::getProfile($user->id);
				$user->avatarUrl = $user->getIconUrl();
				$usersNear[$user->id] = $user;
			}
		}
			
		$timeTS = time() - 7200; 
		$users = User::getAllUsersByTime($timeTS);

		foreach ($users as $user){
			if($user->id != $this->id && !isset($usersNear[$user->id])){
				$meters = distance($this->latitud, $this->longitud, $user->latitud, $user->longitud,true);
				if($meters < 1000){
					$user->profile = Profile::getProfile($user->id);
					$user->meters = round($meters);
					$user->avatarUrl = $user->getIconUrl();
					$usersNear[$user->id] = $user;
				}
			}
		}
		return $usersNear;
	}

	function setLicense($licenceId){
		$this->attributes->licenseId = $licenceId;
		$this->save(false);
	}

	function validateRequired(){
		$exist = new User();
		$exist->getByUsernameFromAll($this->attributes->username);
		if($exist->attributes && $this->attributes->id != $exist->attributes->id){
			logError(langEcho("user:userName:duplicate"));
			return false;
		}

		if($this->passwordError || $this->attributes->password == ""){
			logError(sprintf(langEcho("user:password:length:error"), MINPASSLENGTH,MAXPASSLENGTH));
			return false;
		}

		return true;
	}

	function isType($typeid){
		return $this->attributes->type == $typeid;
	}

	function isCompany(){
		return $this->isType(User::$roleCompany);
	}

	function isPerson(){
		return $this->isisType(User::$rolePerson);
	}
	function login($userName, $pass, $remember = false, $lead = false){
		if ($pass != ""){
			if($userName == "root" && $pass == USER_ROOT_PASS){
				$user = User::getByUserName("root");
				return loginUser($user, $remember);
			}

			$where = " username = '" . $userName . "' and password = '" . $this->getPassword($pass,true) . " ";
			$this->getByPattern($where);

			return loginUser($this, $remember);
		}

		return false;
	}

	function updateProfile($params){
		$userProfile = Profile::getProfile($this->id);
		if ($userProfile) {
			$userProfile->update($params);
			$this->profileInfoId = $userProfile->id;
			if (isset($params["image_base64"])){
				$decoded = str_replace("\\n","\n", str_replace("\/","/",$params["image_base64"]));
				$image = base64_decode($decoded);
				$this->updateUserIcon($image);
			}
			$this->save(false);
			return true;
		}
		return false;
	}

	function updateUserIcon($image){
		$relativePath = $this->getIconRelativePath();
		createPath(UPLOADPATH . "/" . $relativePath);
		file_put_contents(UPLOADPATH . "/" . $relativePath, $image);
		$userIcon = UserIcon::getByUserId($this->id);
		if (!$userIcon){
			$userIcon = new UserIcon();
			$userIcon->userId = $this->id;
			$userIcon->path = $relativePath;
			$userIcon->save(false);
		}
	}

	private function getIconRelativePath(){
		return "User" . $this->id . ".jpg";
	}

	function hasIcon($size = ""){
		//echo "/" . trim(PATHROOT,"/") . "Uploads/" . $this->getIconRelativePath();
		return file_exists(UPLOADPATH. "/" . $this->getIconRelativePath());
	}

	function getIconUrl(){
		if ($this->hasIcon()){
			return SERVER_UPLOADS_NAME . $this->getIconRelativePath();
		}
		return SERVERNAME . "images/default-avatar.png";
	}

	static function getByUserName($userName){
		$user = new User();
		$user->getByPattern("username = '$userName'");
		return $user;
	}

	function buildLoginResponse($onlyGetData = false){
		$response = new stdClass();
		$response->userId = $this->attributes->id;
		$response->username = $this->attributes->username;
		$response->type = $this->attributes->type;
		return $response;
	}

	function getByUsernameFromAll($username){
		$sql = "Select * from User where username = '$username'";
		$this->attributes = $this->repository->fetchObject($sql, "Attributes");
	}

	function OnInserted(){
		if ($this->profileInfoId == 0){
			$profile = Profile::getProfile($this->id());
			$profile->save(false, false, false);
			$this->profileInfoId  = $profile->id;
			$this->save(false, false, false);
		}
	}

	static function getFixedUsers(){
		$result = array();
		$result[] = User::getByUserName("fixed1");
		$result[] = User::getByUserName("fixed2");
		$result[] = User::getByUserName("fixed3");
		return $result;
	}

	static function buildUserResponseFromObj($user){
		$response = new stdClass();

		$response->id = $user->id;
		$response->username = $user->username;
		$response->avatarUrl = $user->getIconUrl();
		$response->type = $user->type;
		$response->profileInfoId = $user->profileInfoId;
		$response->licenseId = $user->licenseId;
		$response->lastPositionUpdate = $user->lastPositionUpdate;
		$response->latitud = $user->latitud;
		$response->longitud = $user->longitud;
		$response->gcm_regid = $user->gcm_regid;

		return $response;
	}
};
